package cz.patamat.support;

import java.util.ArrayList;
import java.util.List;

abstract class AnswerSheet {
	
	/**
	 * Extending classes should use this list to store questions. Otherwise answer sheet methods
	 * wont work.
	 */
	protected List<Question> questions = new ArrayList<Question>();
	
	/**
	 * Get text of answer on given question.
	 * @param questionId
	 * @param answerId
	 * @return null either if answer sheet does not contains question with specified id, or when question 
	 * does not contain answer with specified id.
	 */
	public String getAnswerText(String questionId, String answerId) {
		Question question = getQuestionById(questionId);
		if (question == null) {
			return null;
		}
		Answer answer = question.getAnswerById(answerId);
		if (answer == null) {
			return null;
		}
		return answer.getText();
	}
	
	/**
	 * Get text of question.
	 * @param questionId
	 * @return null if answer sheet does not contain question with specified id.
	 */
	public String getQuestionText(String questionId) {
		Question question = getQuestionById(questionId);
		if (question == null) {
			return null;
		}
		return question.getText();
	}
	
	/**
	 * Mark answer as response to question. Use this method to select responses either
	 * of check boxes or radio buttons questions. It is possible to mark more than one
	 * response by multiple invocation of method with different answer parameter. Concrete
	 * implementation of answer sheet is responsible for correct manipulation with this
	 * method to manage its state correct.  
	 * @param questionId question id which is responding
	 * @param answerId answer id which is mark as a response for given question
	 * @return false either if question with given id does not exist in answer sheet,
	 * or answer with given id does not belong between answers of question.
	 */
	protected boolean markAnswerToQuestion(String questionId, String answerId) {
		Question question = getQuestionById(questionId);
		if (question == null) {
			return false;
		}
		Answer answer = question.getAnswerById(answerId);
		if (answer == null) {
			return false;
		}
		question.markAnswer(answer);
		return true;
	}

	/**
	 * 
	 * @param questionId
	 * @return return null if question with given id does not exists in answer sheet.
	 */
	private Question getQuestionById(String questionId) {
		for (Question question: questions) {
			if (question.getId().equals(questionId)) {
				return question;
			}
		}
		return null;
	}

}
